package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 刘付磊
 * @date 2021/11/12 0012
 */
@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1.将图片上传到阿里云oss
        String upload = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2.调用百度云来判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(upload);
        //2.1如果不包含 抛出异常
        if (!detect){
            throw new BusinessException(ErrorResult.faceError());
        }else {
            //2.2包含人脸，调用API更新.
            UserInfo userInfo =new UserInfo();
            userInfo.setId(Long.valueOf(id));
            userInfo.setAvatar(upload);
            userInfoApi.update(userInfo);
        }

    }

    public UserInfoVo findById(Long id) {
        UserInfo byId = userInfoApi.findById(id);
        UserInfoVo Vo=new UserInfoVo();
        BeanUtils.copyProperties(byId,Vo);
        if(byId.getAge()!=null){
            Vo.setAge(byId.getAge().toString());
        }

        return Vo;
    }

    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}
